package com.zwp.base.state

import android.app.Application
import android.graphics.drawable.Drawable
import android.util.Log
import android.view.View
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import com.zwp.base.R
import com.zwp.base.binding.BindingAction
import com.zwp.base.binding.BindingCommand
import dagger.hilt.android.qualifiers.ApplicationContext


class StateModel(
    var title: String? = null,//标题
    var subTitle: String? = null,//副标题
    var icon: Int? = null, //icon
) {

    /**
     * 网络错误
     */
    val netError = ObservableBoolean(false)

    /**
     * 显示进度
     */
    val isProgress = ObservableBoolean(true)

    /**
     * icon
     */
    val emptyIconRes = ObservableField<Drawable>()


    /**
     * 显示重试按钮
     */
    val showReload = ObservableInt(View.GONE)

    /**
     * 重试按钮文案
     */
    val reloadStr = ObservableField<String>()

    /**
     * 是否显示返回键
     */
    val showBackIcon = ObservableBoolean(false)

    /**
     * 是否显示标题
     */
    val titleVisibility = ObservableInt(View.VISIBLE)


    /**
     * 是否需要拦截掉触摸事件，默认true
     */
    val interceptTouch = ObservableBoolean(true)

    /**
     * 背景色
     */
    val backgroundColor = ObservableInt(R.color.white)


    /**
     * 是否显示副标题
     */
    var isShowErrorTitle = true


    /**
     * 缺省页顶部间距
     */
    val marginTop = ObservableInt()

    /**
     * 网络异常时显示的重试文案
     */
    private var errorReloadStr: String = ""

    /**
     * 无网络时显示的重试文案
     */
    private var emptyReloadStr: String = ""

    /**
     * 加载文字
     */
    val loadingContent = ObservableField<String>("")

    @ApplicationContext
    lateinit var application: Application

    var emptyState: EmptyState = EmptyState.NORMAL
        set(value) {
            field = value
            update()
            onEmptyStateChangeListener?.onChange(field)
        }

    var onEmptyStateChangeListener: OnEmptyStateChangeListener? = null
    var reloadClick: (() -> Unit?)? = null
    var backClick: (() -> Unit?)? = null


    fun update() {
        isProgress.set(emptyState == EmptyState.PROGRESS)
        netError.set(emptyState == EmptyState.NET_ERROR)
        when (emptyState) {
            EmptyState.NORMAL -> setEmpty()
            EmptyState.NET_ERROR -> setNetError()
            EmptyState.NOT_AVAILABLE -> setAvailable()
            else -> setNormal()
        }
        // 更新后，清掉资源，避免出现复用问题
        icon = null
        title = null
        subTitle = null
    }

    private fun setNormal() {
        icon = R.mipmap.ic_launcher
    }

    private fun setAvailable() {

    }

    private fun setNetError() {

    }

    private fun setEmpty() {

    }

    val reloadOnClick = BindingCommand<BindingAction>({
        reloadClick?.invoke()
    })

    val onBackClick = BindingCommand<BindingAction>({
        backClick?.invoke()
    })
}
